<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Redis;
use App\Models\Company;
use App\Http\Requests;
use EasyWeChat;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use App\Models\Order as payOrder;
use Carbon\Carbon;

class WechatController extends Controller
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        $wechat = app('wechat');
        $wechat->server->setMessageHandler(function ($message) {
            return "欢迎关注";
        });
        ob_clean();
        return $wechat->server->serve();
    }



    //移到没基类的类中
    public function pay_validate(Request $Request)
    {
        $app = new Application(config('wechat'));
        $response = $app->payment->handleNotify(function ($notify, $successful) {
            Redis::hset('kpi_order_pay_error', $notify->out_trade_no, json_encode($notify));
            if (substr($notify->out_trade_no, -3) == 'kpi') {
                if ($successful) {
                    Redis::hset('kpi_order_pay_status', $notify->out_trade_no, json_encode($notify));
                    $kpi_key = $notify->out_trade_no;
                    $order = json_decode(Redis::hget('kpi_order', $kpi_key));
                    $pay_order = new payOrder;
                    //订单信息
                    $pay_order->user_id = $order->user_id;
                    $pay_order->order_sn = $order->out_trade_no;
                    $pay_order->goods_type = $order->goods_type;   //3种中的哪一种
                    $pay_order->pay_status = 1;
                    $pay_order->pay_type = $order->pay_type;
                    $pay_order->goods_name = $order->body;
                    $pay_order->corpid = $order->corpid;
                    //支付信息
                    $pay_order->sign = $notify->sign;
                    $pay_order->time_end = $notify->time_end;
                    $pay_order->total_fee = $notify->total_fee / 100;
                    $pay_order->transaction_id = $notify->transaction_id;
                    $pay_order->save();
                    //修改续费时间
                    $this->add_expiry($order->corpid,$order->goods_type);

                } else {
                    Redis::hset('kpi_order_pay_error', $notify->out_trade_no, json_encode($notify));
                    //支付失败
                }
                return true;
            }
        });
        return $response;
    }


    private function add_expiry( $corpid,$type){
        $Company=Company::where('id',$corpid)->first();
        $now=Carbon::now();
        $expire=Carbon::parse($Company->expire_at);
        if($now->gte($expire)){
            $Company->expire_at=$now->modify('+'.$type.'year');
        }else{
            $Company->expire_at=$expire->modify('+'.$type.'year');
        }
        $Company->save();
    }
}
